package org.arch_learn.io.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NioChannelServerDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        //1.打开一个服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(9999));
        //3.通道默认是阻塞的，这里需要手动设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        System.out.println("服务端启动成功！");
        //4.检查是否有客户端连接，如果有客户端连接，会返回相应通道
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                System.out.println("无客户端连接则去做其他事情");
                Thread.sleep(10000);
                continue;
            }
            //5.获取客户端传来的数据，并把数据放到bytebuffer缓冲区中
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = socketChannel.read(byteBuffer);
            //read如果是正数则代表本次读到的有效字节数
            //read如果是0则代表本次没有读到数据
            //read如果是负数（只会为-1）则代表已经读到末尾
            String requestMessage = new String(byteBuffer.array(), 0, read, StandardCharsets.UTF_8);
            System.out.println("收到客户端发送的消息：" + requestMessage);

            //6.给客户端写回数据
            ByteBuffer responseByteBuffer = ByteBuffer.wrap("response".getBytes(StandardCharsets.UTF_8));
            socketChannel.write(responseByteBuffer);
            //7.释放资源
            socketChannel.close();
        }



    }
}
